//
//  BatchOptController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/5/17.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "BatchOptController.h"
#import "JFBLoadingAnimation.h"
#import "JFBMerchandiseDS.h"
#import "BatchOptCell.h"
#import "UIButton+SelectFix.h"

@interface BatchOptController()
- (IBAction)selectAllAction:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *upShelfLabel;
@property (weak, nonatomic) IBOutlet UIButton *upShelfCheck;
@property (weak, nonatomic) IBOutlet UIButton *downShelfCheck;
@property (weak, nonatomic) IBOutlet UILabel *downShelfLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *batUpBtn;
@property (weak, nonatomic) IBOutlet UIButton *batDownBtn;
@property (weak, nonatomic) IBOutlet UILabel *selectedCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *selectAllBtn;
@property (weak, nonatomic) IBOutlet UILabel *selectAllLabel;
- (IBAction)allUPAction:(id)sender;
- (IBAction)allDownAction:(id)sender;

@property (nonatomic, strong) NSMutableArray *selfItems;
@property (nonatomic, strong) NSMutableArray *currentItems;
//0-全部 1-上架的 2-下架的
@property (nonatomic, assign) NSUInteger currentFilter;
@end

@implementation BatchOptController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.currentItems = [@[] mutableCopy];
    
    if( self.merchandiseCategory ) {
        NSString *up = [NSString stringWithFormat:@"已上架商品(%lu)", (unsigned long)self.merchandiseCategory.shelvesNum];
        NSString *down = [NSString stringWithFormat:@"未上架商品(%lu)", (unsigned long)(self.merchandiseCategory.total - self.merchandiseCategory.shelvesNum)];
        
        self.upShelfLabel.text = up;
        self.downShelfLabel.text = down;
    }
    
    [((UIButton_SelectFix*)self.upShelfCheck) setImage:[UIImage imageNamed:@"check2"] forButtonState:UIControlStateNormal];
    [((UIButton_SelectFix*)self.upShelfCheck) setImage:[UIImage imageNamed:@"check2_on"] forButtonState:UIControlStateSelected];
    [((UIButton_SelectFix*)self.downShelfCheck) setImage:[UIImage imageNamed:@"check2"] forButtonState:UIControlStateNormal];
    [((UIButton_SelectFix*)self.downShelfCheck) setImage:[UIImage imageNamed:@"check2_on"] forButtonState:UIControlStateSelected];
    
    CGRect size = CGRectMake(0, 0, 66, 33);
    
    UIColor * importColor = TextColorImportButton;
    [self.batDownBtn setTitleColor:importColor forState:UIControlStateNormal];
    [self.batDownBtn setBackgroundColor:[UIColor clearColor]];
    [self.batDownBtn.layer setMasksToBounds:YES];
    [self.batDownBtn.layer setCornerRadius:16.0]; //设置矩形四个圆角半径
    [self.batDownBtn.layer setBorderWidth:1.0]; //边框宽度
    [self.batDownBtn.layer setBorderColor: importColor.CGColor];
    self.batDownBtn.bounds = size;
    self.batDownBtn.frame = CGRectMake(self.view.bounds.size.width - kOrderCellSpacing - 66, self.batDownBtn.frame.origin.y, 66, 33);
    
    UIColor * specialColor = TextColorSpecialButton;
    [self.batUpBtn setTitleColor:specialColor forState:UIControlStateNormal];
    [self.batUpBtn setBackgroundColor:[UIColor clearColor]];
    [self.batUpBtn.layer setMasksToBounds:YES];
    [self.batUpBtn.layer setCornerRadius:16.0]; //设置矩形四个圆角半径
    [self.batUpBtn.layer setBorderWidth:1.0]; //边框宽度
    [self.batUpBtn.layer setBorderColor: specialColor.CGColor];
    self.batUpBtn.bounds = size;
    self.batUpBtn.frame = CGRectMake(self.view.bounds.size.width - kOrderCellSpacing*2 - 132, self.batDownBtn.frame.origin.y, 66, 33);
    
    [((UIButton_SelectFix*)self.selectAllBtn) setImage:[UIImage imageNamed:@"check2"] forButtonState:UIControlStateNormal];
    [((UIButton_SelectFix*)self.selectAllBtn) setImage:[UIImage imageNamed:@"check2_on"] forButtonState:UIControlStateSelected];
    
    UITapGestureRecognizer *upGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onUpLabelClick:)];
    self.upShelfLabel.userInteractionEnabled=YES;
    upGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    upGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.upShelfLabel addGestureRecognizer:upGesture];
    
    UITapGestureRecognizer *downGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onDownLabelClick:)];
    self.downShelfLabel.userInteractionEnabled=YES;
    downGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    downGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.downShelfLabel addGestureRecognizer:downGesture];
    
    UITapGestureRecognizer *selectAllGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onSelectAllLabelClick:)];
    self.selectAllLabel.userInteractionEnabled=YES;
    upGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    upGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.selectAllLabel addGestureRecognizer:selectAllGesture];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    if( self.merchandiseCategory ) {
        [self reload:nil];
//        [self refreshCount];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(merchandiseSelect:) name:@"merchandiseSelect" object:nil];
}

- (void)merchandiseSelect:(NSNotification *)notification {
    NSUInteger merchandiseId = [[notification.userInfo objectForKey:@"merchandiseId"] intValue];
    
    for( JFBMerchandiseDS * ds in self.currentItems ) {
        if( ds.mpId == merchandiseId ) {
            ds.mpURL = [ds.mpURL isEqualToString:@"on"] ? @"off" : @"on";
        }
    }
    [self refreshSelectedCount];
    [self.tableView reloadData];
    
}

-(void)setItems:(NSArray *)items {
    self.selfItems = [items mutableCopy];
}

-(void)reload {
    [self reload:nil];
}

-(void)onUpLabelClick:(UITapGestureRecognizer *)sender{
    [self upBtnClick:nil];
}

-(void)onDownLabelClick:(UITapGestureRecognizer *)sender{
    [self downBtnClick:nil];
}

-(void)onSelectAllLabelClick:(UITapGestureRecognizer *)sender{
    [self selectAllAction:nil];
}

-(void)refreshSelectedCount {
    int c = 0;
    for( JFBMerchandiseDS *ds in self.currentItems ) {
        if( [ds.mpURL isEqualToString:@"on"] ) {
            c += 1;
        }
    }
    self.selectedCountLabel.text = [NSString stringWithFormat:@"已选%d件商品", c];
}

- (void)reload:(__unused id)sender {
    [self tableViewDataSourceFilte];
    [self.tableView reloadData];
}

-(void)tableViewDataSourceFilte{
    [self.currentItems removeAllObjects];
    for( JFBMerchandiseDS *ds in self.selfItems ) {
        if( self.currentFilter == -1 ||  (ds.mpStatus && self.currentFilter == 4) || (!ds.mpStatus && self.currentFilter == 5)  ) {
            [self.currentItems addObject:ds];
        }
    }
    [self.tableView reloadData];
    [self refreshSelectedCount];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.currentItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JFBMerchandiseDS * ds = self.currentItems[indexPath.row];
    
    BatchOptCell *cell = [tableView dequeueReusableCellWithIdentifier:@"batchOptCellIdentifier" forIndexPath:indexPath];
    
    cell.merchandise = ds;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    JFBMerchandiseDS * ds = self.currentItems[indexPath.row];
    
    ds.mpURL = [ds.mpURL isEqualToString:@"on"] ? @"off" : @"on";
    
    BatchOptCell *cell = (BatchOptCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    cell.merchandise = ds;
    
    [self refreshSelectedCount];
}



-(void)viewDidLayoutSubviews {
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (IBAction)downBtnClick:(id)sender {
    if( self.currentFilter == 8 ) {
        [self.downShelfCheck setSelected:true];
        self.currentFilter = 5;
    }else if( self.currentFilter == 4 ) {
        [self.upShelfCheck setSelected:false];
        [self.downShelfCheck setSelected:true];
        self.currentFilter = 5;
    }else {
        [self.downShelfCheck setSelected:false];
        self.currentFilter = 8;
    }
    [self tableViewDataSourceFilte];
}

- (IBAction)upBtnClick:(id)sender {
    if( self.currentFilter == 8 ) {
        [self.upShelfCheck setSelected:true];
        self.currentFilter = 4;
    }else if( self.currentFilter == 4 ) {
        [self.upShelfCheck setSelected:false];
        self.currentFilter = 8;
    }else {
        [self.upShelfCheck setSelected:true];
        [self.downShelfCheck setSelected:false];
        self.currentFilter = 4;
    }
    [self tableViewDataSourceFilte];
}

- (IBAction)selectAllAction:(id)sender {
    [self.selectAllBtn setSelected:!self.selectAllBtn.selected];
    for( JFBMerchandiseDS * ds in self.currentItems ) {
        ds.mpURL = self.selectAllBtn.selected ?  @"on" : @"off";
    }
    [self.tableView reloadData];
    [self refreshSelectedCount];
}

-(NSString*)fetchProductIds {
    NSMutableArray * ids = [@[] mutableCopy];
    for( JFBMerchandiseDS *ds in self.currentItems ) {
        if( [ds.mpURL isEqualToString:@"on"] ) {
            [ids addObject:[NSNumber numberWithInteger:ds.mpId]];
        }
    }
    if( ids.count == 0 ) {
        return nil;
    }
    return [NSString stringWithFormat:@"%@,", [ids componentsJoinedByString:@","]];
}

- (IBAction)allUPAction:(id)sender {
    NSLog(@"批量上架");
    NSString * ids = [self fetchProductIds];
    if( ids == nil ) {
        [JFBUIAnimation topTips:self.tableView tipString:@"没有选择任何商品" delegate:nil];
        return;
    }
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    [JFBMerchandiseDS batchUpAndDownShelf:^(BOOL isSuccess, NSString *message, NSError *error) {
        [SVProgressHUD dismiss];
        [JFBUIAnimation alertTips:message];
        if( isSuccess ) {
//            [self refreshCount];
            [self.delegate reload];
            [self.navigationController popViewControllerAnimated:TRUE];
        }
        
    } productIds:ids optFlag:1];
}

- (IBAction)allDownAction:(id)sender {
    NSString * ids = [self fetchProductIds];
    if( ids == nil ) {
        [JFBUIAnimation topTips:self.tableView tipString:@"没有选择任何商品" delegate:nil];
        return;
    }
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    [JFBMerchandiseDS batchUpAndDownShelf:^(BOOL isSuccess, NSString *message, NSError *error) {
        [SVProgressHUD dismiss];
        [JFBUIAnimation alertTips:message];
        if( isSuccess ) {
            [self.delegate reload];
            [self.navigationController popViewControllerAnimated:TRUE];
        }
    } productIds:ids optFlag:0];
}
@end
